package net.lym.es.doc;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.lym.es.pojo.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

/**
 * ES测试 : 文档数据插入
 */
public class ESTest_Doc_Insert {
    public static void main(String[] args) throws Exception {
        // 创建 ES 客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

        // 新增文档 - 请求对象
        IndexRequest request = new IndexRequest();
        // 设置索引及唯一性标识
        request.index("user").id("1001");
        // 创建数据对象
        User user = new User();
        user.setName("zhangsan");
        user.setAge(30);
        user.setSex("男");
        // 向ES插入数据，必须将数据转换位JSON格式
        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(user);
        // 添加文档数据，数据格式为JSON格式
        request.source(userJson, XContentType.JSON);
        // 客户端发送请求，获取响应对象
        IndexResponse response = esClient.index(request, RequestOptions.DEFAULT);
        // 打印结果信息
        System.out.println("_index:" + response.getIndex());    // 索引
        System.out.println("_id:" + response.getId());          // 唯一性标识
        System.out.println("_result:" + response.getResult());  // 结果

        // 关闭 ES 客户端
        esClient.close();
    }
}
